package com.boarsoft.boar.soagov.lib.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.common.Constants;
import com.boarsoft.boar.dir.DirBiz;
import com.boarsoft.boar.dir.bean.DirTreeNode;
import com.boarsoft.boar.entity.DirInfo;
import com.boarsoft.boar.entity.LibInfo;
import com.boarsoft.boar.lib.action.LibAction;
import com.boarsoft.boar.soagov.entity.LibSoagovInfo;
import com.boarsoft.common.Authorized;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.JsonUtil;

@RestController
@RequestMapping("/lib")
public class LibSoagovAction extends LibAction {
	@Autowired
	private DirBiz dirBiz;

	@RequestMapping("/save.do")
	@Authorized(code = "lib.save")
	public ReplyInfo<Object> save(String parentId, LibSoagovInfo o) {
		if (Util.strIsEmpty(o.getId())) {
			return this.add(parentId, o);
		}
		return this.update(o);
	}

	public ReplyInfo<Object> add(String parentId, LibSoagovInfo o) {
		DirInfo p = dirBiz.get(parentId);
		if (p == null) {
			return Constants.REPLY_WARN_INVALID;
		}
		DirInfo d = new DirInfo();
		d.setParentId(parentId);
		d.setLevel(p.getLevel() + 1);
		d.setPath(String.format("%s/%s", p.getPath(), p.getId()));
		d.setCode(o.getCode());
		d.setName(o.getName());
		d.setType(DirInfo.TYPE_LIB);

		LibSoagovInfo c = new LibSoagovInfo();
		c.setCode(o.getCode());
		c.setStatus(LibInfo.STATUS_INUSE);// 应用默认为启用
		c.setName(o.getName());
		c.setLevel(o.getLevel());
		c.setVer(o.getVer());
		c.setType(o.getType());
		c.setMemo(o.getMemo());

		String projId = dirBiz.lookup(p, DirInfo.TYPE_PROJ);
		if (Util.strIsNotEmpty(projId)) {
			c.setProjId(projId);
		}
		ReplyInfo<Object> ro = libBiz.add(d, c);
		if (ro.isSuccess()) {
			DirTreeNode dtn = new DirTreeNode((DirInfo) ro.getData());
			return new ReplyInfo<Object>(true, JsonUtil.from(dtn));
		}
		return ro;
	}

	@RequestMapping("/update.do")
	@Authorized(code = "lib.update")
	public ReplyInfo<Object> update(LibSoagovInfo o) {
		DirInfo d = dirBiz.get(o.getId());
		d.setName(o.getName());
		LibSoagovInfo c = (LibSoagovInfo) libBiz.get(o.getId());
		c.setCode(o.getCode());
		c.setLevel(o.getLevel());
		c.setName(o.getName());
		c.setLevel(o.getLevel());
		c.setVer(o.getVer());
		c.setType(o.getType());
		c.setMemo(o.getMemo());
		c.setStatus(o.getStatus());
		ReplyInfo<Object> ro = libBiz.update(d, c);
		if (ro.isSuccess()) {
			DirTreeNode dtn = new DirTreeNode((DirInfo) ro.getData());
			return new ReplyInfo<Object>(true, dtn);
		}
		return ro;
	}
}